<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
function themeInit($self) {}

/*获取博文封面*/
function getFirstCover($d)
{
    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", $d->content, $matches);  //通过正则式获取图片地址
    $thumb = null;
    if (isset($matches[1][0])) {
        $thumb = $matches[1][0];
    }
    return $thumb ? $thumb : randBing(1);
}


/*获取文章的地图坐标和相册路径*/
function getLocationAndAlbum($d)
{
    $location_lng = $d->fields->mapLng;
    $location_lat = $d->fields->mapLat;
    $albumPath = $d->fields->albumPath;
    return ["lng" => $location_lng, "lat" => $location_lat, "album" => $albumPath];
}
/*获取博文所有图片数组*/
function getCoverList($d)
{
    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", $d->content, $matches);
    if (isset($matches[1])) {
        return $matches[1];
    }
    return null;
}
/*博文统计*/
function postCount()
{
    $db = Typecho_Db::get();
    // 查询出文章数量并转换为数组
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.contents')->where('type = ?', 'post')->where('status = ?', 'publish'));
    // 返回文章数量
    $res = $count['COUNT(*)'];
    return str_pad($res, 2, '0', STR_PAD_LEFT);
}
/*评论统计*/
function commentsCount()
{
    $db = Typecho_Db::get();
    // 查询出评论数量并转换为数组
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.comments')->where('status = ?', 'approved'));
    // 返回评论数量
    return $count['COUNT(*)'];
}
/*分类统计*/
function categoryCount()
{
    $db = Typecho_Db::get();
    // 查询出分类数量并转换为数组
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.metas')->where('type = ?', 'category'));
    // 返回分类数量
    $res = $count['COUNT(*)'];
    return str_pad($res, 2, '0', STR_PAD_LEFT);
}
/*标签统计*/
function tagCount()
{
    $db = Typecho_Db::get();
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.metas')->where('type = ?', 'tag'));
    $res = $count['COUNT(*)'];
    return str_pad($res, 2, '0', STR_PAD_LEFT);
}
/*点赞量*/
function agreeCount()
{
    $db = Typecho_Db::get();
    // 对文章表的 agree 字段进行求和并把查询出的结果转换为数组
    $count = $db->fetchRow($db->select('SUM(agree) AS agreeCount')->from('table.contents'));
    // 返回总点赞数
    return $count['agreeCount'];
}
/**
 获取所有分类
 */
function getAllCategories() {
    $db = Typecho_Db::get();
    $categories = $db->fetchAll($db->select()->from('table.metas')->where('type=?', 'category'));
    return $categories;
}

/*评论数量排名前5*/
//Array {title,link,commentsNum}
function topCommentPost($num)
{
    $db = Typecho_Db::get();
    // 查询出 5 条评论数最大的文章，按照评论数从大到小排序，然后把查询出的数据转换为数组
    $top5Post = $db->fetchAll($db->select()->from('table.contents')->where('type = ?', 'post')->where('status = ?', 'publish')->order('commentsNum', Typecho_Db::SORT_DESC)->offset(0)->limit($num));
    // 用来存储文章信息的数组
    $postList = array();
    foreach ($top5Post as $post) {
        // 使用 Typecho 提供的 API 获取每篇文章的链接地址
        $post = Typecho_Widget::widget('Widget_Abstract_Contents')->filter($post);


        //"/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]/"
        //"/!\[(.*?)\]\((.*?)\)/"
        preg_match_all("/https:\/\/((?!https:\/\/).)+?(\.jpg|\.png|\.webp)/", $post['text'], $matches);  //通过正则式获取图片地址
        if (isset($matches[0][0])) {
            $cover = $matches[0][0];
        } else {
            $cover = 'null';
        }
        // 把文章标题、链接、点赞数加入数组
        array_push($postList, array(
            'title' => $post['title'],
            'link' => $post['permalink'],
            'commentsNum' => $post['commentsNum'],
            'cover' => $cover,

        ));
    }
    // 返回 5 篇文章的标题、链接、点赞数
    return $postList;
}
/*获取所有独立页面*/
function getPages($num = -1) {
    $db = Typecho_Db::get();
    $select = $db->select()->from('table.contents')
                          ->where('type = ?', 'page')
                          ->where('status = ?', 'publish')
                          ->order('order', Typecho_Db::SORT_DESC);

    if ($num > 0) {
        $select->limit($num);
    }

    $pages = $db->fetchAll($select);
    $list = array();

    foreach ($pages as $post) {
        $windowSize = getCustom($post['cid'],'windowSize');
        array_push($list, array(
            'title' => $post['title'],
            'link' => $post['slug'],
            'size' => $windowSize
        ));
    }
    return $list;
}

//获取自定义字段
function getCustom($cid, $key){
    $f=Typecho_Widget::widget('Widget_Archive@'.$cid,'pageSize=1&type=page', 'cid='.$cid);
    return $f->fields->$key;
}


// function getPages()
//  {
//      $db = Typecho_Db::get();
//      $pages = $db->fetchAll($db->select()->from('table.contents')->where('type = ?', 'page')->where('status = ?', 'publish')->order('order', Typecho_Db::SORT_DESC)); //->limit($num));
//      $list = array();
//      foreach ($pages as $post) {
//          array_push($list, array(
//              'title' => $post['title'],
//              'link' => $post['slug'],
//              'size' => $post->fields['windowSize']
//          ));
//      }
//      return $list;
//  }

/*从封面图片列表中随机取一条*/
function getCoverOne()
{
    $val = trim(Helper::options()->coverImgList);
    $list = explode(',', $val);
    $i = array_rand($list);
    return $list[$i];
}

/*获取各分类下的文章数量*/
//Array {name,count}
function categoryPostCount()
{
    $db = Typecho_Db::get();
    // 查询出每个分类的文章数量并转换为数组
    $count = $db->fetchAll($db->select('name', 'count')->from('table.metas')->where('type = ?', 'category'));
    // 如果没有查询到数据就返回空数组
    if (count($count) < 1) {
        return array();
    }
    // 返回每个分类的文章数量
    return $count;
}


/*获取新浪热词*/
function getSinaHotWord()
{
    $cont = file_get_contents('http://www.sina.com.cn/api/hotword.json');
    if (!empty($cont)) {
        return json_decode($cont, true)['result']['data'];
    } else {
        return "";
    }
}


/*解析RSS*/
function getRss($url)
{
    $cont = file_get_contents($url);
    $r = [];
    if (!empty($cont)) {
        $d = new DOMDocument;
        $d->load($cont);
        $list = $d->getElementsByTagName('enclosure');
        foreach ($list as $item) {
            array_push($r, ["title" => $item->getAttribute('title'), "link" => $item->getAttribute('link'), "desc" => $item->getAttribute('description'), "date" => date('Y-m-d H:i', strtotime($item->getAttribute('pubDate')))]);
        }
    }

    return $r;
}

/**
 * 解析rss
 */
function loadRSS($url)
{
    // 定义RSS源的URL
    $rss_url = $url; //'http://news.baidu.com/n?cmd=1&class=civilnews&tn=rss';

    // 使用file_get_contents函数获取RSS源的内容
    $rss_content = file_get_contents($rss_url);

    // 检查是否成功获取了内容
    if ($rss_content === FALSE) {
        die('无法获取RSS源内容');
    }

    // 创建一个新的SimpleXMLElement对象来解析RSS内容
    $rss = new SimpleXMLElement($rss_content);

    // 遍历RSS馈送中的每个条目
    // foreach ($rss->channel->item as $item) {
    //     // 输出条目的标题和链接
    //     echo '标题: ' . $item->title . '<br>';
    //     echo '链接: <a href="' . $item->link . '">' . $item->link . '</a><br>';
    //     echo '描述: ' . $item->description . '<br><br>';
    // }
    return $rss;
}

/*获取bing今日图片*/
function getBingToday()
{
    // 设置API地址（这里使用Bing每日图片API作为示例）
    $api_url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1';

    // 使用curl获取API响应
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);

    // 解析JSON响应
    $data = json_decode($response, true);

    if ($data && isset($data['images'][0]['url'])) {
        // 构建完整的图片URL
        //$image_url = 'https://www.bing.com' . $data['images'][0]['url'];

        // 返回JSON格式的结果
        $res = $data['images'][0];
        $res['url'] = 'https://www.bing.com' . $data['images'][0]['url'];
        $resultData = saveBingImg2DB($res);
        $res['monthList'] = $resultData['listofmonth'];
        $res['month'] = $resultData['monthlist'];
        $res['count'] = $resultData['count'];
        return $res;
    } else {
        // 如果获取失败，返回错误信息
        return null;
    }

    /*
    [startdate] => 20241204
    [fullstartdate] => 202412041600
    [enddate] => 20241205
    [url] => https://www.bing.com/th?id=OHR.MonoTufa_ZH-CN4998806540_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
    [urlbase] => /th?id=OHR.MonoTufa_ZH-CN4998806540
    [copyright] => 莫诺湖的石灰华地层，加利福尼亚州，美国 (© Susanna Patras/TANDEM Stills + Motion)
    [copyrightlink] => https://www.bing.com/search?q=%E5%8A%A0%E5%88%A9%E7%A6%8F%E5%B0%BC%E4%BA%9A%E5%B7%9E%E8%8E%AB%E8%AF%BA%E6%B9%96&form=hpcapt&mkt=zh-cn
    [title] => 石灰华塔的崛起
    [quiz] => /search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20241204_MonoTufa%22&FORM=HPQUIZ
     [wp] => 1
     [hsh] => 55d048ad3b661ebcb5d478a5fcecea5a
     [drk] => 1 [top] => 1 [bot] => 1 [hs] => Array ( )
    */
}

/* 从数据库中随机取一张图片地址 */
function randBing($num)
{
    $db = new SQLite3('sql.db');
    $liststmt = $db->prepare("select * from bings order by random() limit " . $num);
    $listRes =  $liststmt->execute();
    if($num<2){
        return  $listRes->fetchArray(SQLITE3_ASSOC)['urlstr'];
    }else{
        $list = [];
        while ($row = $listRes->fetchArray(SQLITE3_ASSOC)) {
            $list[] = $row;
        }
        $db->close();
        return $list;
    }
}

/*获取指定月份图片列表*/
function getBingByMonth($ym)
{
    $db = new SQLite3('sql.db');
    $stmt1 = $db->prepare("select * from bings where datestr like '" . $ym . "%' order by id desc");
    $result = $stmt1->execute();
    $list = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $list[] = $row;
    }
    $db->close();
    $pattern = '/"/'; // 正则表达式模式，匹配双引号
    $replacement = ""; // 替换成的字符，即单引号
    foreach ($list as $key => $val) {
        $list[$key]['title'] = preg_replace($pattern, $replacement, $val['title']);
        $list[$key]['date_cn'] = substr($val['datestr'], 0, 4) . '年' . substr($val['datestr'], 4, 2) . '月' . substr($val['datestr'], 6, 2) . '日';
    }
    return $list;
}

/*保存必应图片到数据库*/
function saveBingImg2DB($obj)
{
    $db = new SQLite3('sql.db');
    //创建一个表（如果不存在）
    $db->exec("CREATE TABLE IF NOT EXISTS bings (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        datestr TEXT,
        title TEXT,
        urlstr TEXT ,
        copyright TEXT,
        copyrightlink TEXT
    )");

    //获取月份列表
    $liststmt = $db->prepare("SELECT * FROM bings b1 WHERE b1.datestr = ( SELECT MIN(b2.datestr) FROM bings b2 WHERE b2.datestr LIKE (SUBSTR(b1.datestr, 1, 6) || '%') ) ORDER BY b1.datestr");
    $listRes =  $liststmt->execute();
    $monthList = [];
    while ($row = $listRes->fetchArray(SQLITE3_ASSOC)) {
        $monthList[] = $row;
    }

    // 读取当月数据
    $stmt1 = $db->prepare("select * from bings where datestr like '" . date('Ym') . "%' order by id desc");
    $result = $stmt1->execute();
    $listOfMonth = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $listOfMonth[] = $row;
    }

    // 数据总数
    $sql = "select count(*) from bings";
    $total = $db->querySingle($sql);


    $alreadySave = $db->query("select count(*) from bings where datestr='" . $obj['startdate'] . "'");
    $res = $alreadySave->fetchArray(SQLITE3_ASSOC);
    $count = $res['count(*)'];

    if ($count > 0) {
        $db->close();
        return ['listofmonth' => $listOfMonth, 'monthlist' => $monthList, 'count' => $total];
    }

    // 插入数据
    $stmt = $db->prepare("INSERT INTO bings (datestr, title, urlstr, copyright, copyrightlink) VALUES (:datestr, :title, :urlstr, :copyright, :copyrightlink)");
    $stmt->bindValue(':datestr', $obj['startdate']);
    $stmt->bindValue(':title', $obj['title']);
    $stmt->bindValue(':urlstr', $obj['url']);
    $stmt->bindValue(':copyright', $obj['copyright']);
    $stmt->bindValue(':copyrightlink', $obj['copyrightlink']);
    $stmt->execute();
    $db->close();
    return ['listofmonth' => $listOfMonth, 'monthlist' => $monthList, 'count' => $total];;
}


/*模板变量设置*/
function themeConfig($form)
{
    //网站描述简介
    $site_desc = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'site_desc',
        null,
        null,
        _t('网站简介'),
        _t('')
    );
    $form->addInput($site_desc);
    $site_cover = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'site_cover',
        null,
        null,
        _t('网站简介的封面'),
        _t('')
    );
    $form->addInput($site_cover);

    //评论开关
    $post_comment = new Typecho\Widget\Helper\Form\Element\Radio('post_comment', array('1' => '开启', '2' => '关闭'), '1', _t('是否启用内容评论'));
    $form->addInput($post_comment);


    //是否首页显示幻灯片
    $home_corousel = new Typecho\Widget\Helper\Form\Element\Radio('home_corousel', array('1' => '开启', '2' => '关闭'), '1', _t('是否启用首页幻灯片'));
    $form->addInput($home_corousel);
}



/*新建文章时的附加参数*/
function themeFields($layout)
{
    // $album_json = new Typecho_Widget_Helper_Form_Element_Textarea('album_json', null, null, _t('相册JSON路径'), _t('指向data.json文件'));
    // $layout->addItem($album_json);
    //wmd-more-button
    include_once("../usr/themes/2025/themeInner/functions.html");

    $mapLng = new Typecho_Widget_Helper_Form_Element_Text('mapLng', null, null, _t('地理经度'), _t('调用$field = $this->fields->mapLng;<br/>输出$this->fields->mapLng();'));
    $mapLat = new Typecho_Widget_Helper_Form_Element_Text('mapLat', null, null, _t('地理维度'), _t('调用$field = $this->fields->mapLat;<br/>输出$this->fields->mapLat();'));
    $layout->addItem($mapLat);
    $layout->addItem($mapLng);
//
//     $albumPath = new Typecho_Widget_Helper_Form_Element_Text('albumPath', null, null, _t('相册路径'), _t('示例：/albums/51/'));
//     $layout->addItem($albumPath);

    $windowSize = new Typecho\Widget\Helper\Form\Element\Radio('windowSize', array('large' => '大窗口', 'small' => '小窗口'), 'large', _t('请选择窗口尺寸'));
    $layout->addItem($windowSize);

    $isPhoto = new Typecho\Widget\Helper\Form\Element\Radio('isPhoto', array('yes' => '这是一个图册', 'no' => '这是普通博文'), 'no', _t('请选择博文类型'));
    $layout->addItem($isPhoto);

    $repost = new Typecho_Widget_Helper_Form_Element_Textarea('repost', null, null, _t('转载信息'), _t('选填，无转载信息可留空'));
    $layout->addItem($repost);
}
